package com.hp.common.tool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateTool {
    private final static String DEFAULT_FORMART = "yyyy-MM-dd HH:mm:ss";

    public DateTool() {
    }

    /**
     * 字符串转时间
     * @param source
     * @param format
     * @return
     */
    public static Date stringToDate(String source,String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(source);
        } catch (ParseException e) {
            date = new Date();
        }
        return date;
    }

    public static Date stringToDate(String source){
        return stringToDate(source,DEFAULT_FORMART);
    }

    /**
     * 日期转字符串
     * @param date
     * @param format
     * @return
     */
    public static String dateToString(Date date,String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return sdf.format(date);
    }

    public static String dateToString(Date date){
        return dateToString(date,DEFAULT_FORMART);
    }

}
